<?php 
/*DEE_DESC
$attach=array(
	//Если блоку нужно выбрать место расположения
	'position'=>true,
	//Название блока будет выведно в качестве заголовка
	'title'=>'Список товаров',
	//Необходимые параметры
	'fields'=>array(
		'title'=>array('title'=>'Заголовок блока','desc'=>'pp'),
		'is_blue'=>array('type'=>'checkbox','title'=>'Цвет фона','desc'=>'Синий'),
		'js_map'=>array('type'=>'file','title'=>'Файл карты контактов','root_path'=>'js/site/contacts','extensions'=>array('js'))
	),
	//Приложения которые будут выводится дополнительно при выборе данного шаблона
	'attaches'=>array(
		array(
			//Тип приложения ОБЯЗАТЕЛЬНОЕ
			'type'=>'file',
			//Описание поля ОБЯЗАТЕЛЬНОЕ не для блоков
			'desc'=>'Картинка товара в категории',
			//Название поля для занесения в базу ОБЯЗАТЕЛЬНОЕ
			'name'=>'category_product_image',
			//Параметры аттача
			'params'=>array(
				'root_path'=>'images/products',
				'extensions'=>array('jpeg','jpg','gif','png')
				)
			)
	)); 
//DEE_DESC_END*/
class store_product_list extends Load_use
{
	
	function getBlock()
	{
		$ny_products = array();
		$pr_codes = $definite_bonus_clause = '';
		
		if( isset($this->params['templ']) ) {
			if( $this->params['templ'] == 'ny_products' ) {
				if( isset($_GET['bonus']) ) {
					$definite_bonus_clause = "where bonus = {$_GET['bonus']}";	 
				}
				
				$this->conn->query("SELECT product_code, bonus FROM ny_promo_products {$definite_bonus_clause}");
				
				while( $row = $this->conn->fetch() ) {
					$ny_products[$row->product_code] = $row->bonus;
				}
				
				foreach( $ny_products as $pr_code=>$pr_bonus )
					$pr_codes .= $pr_code.', ';
				
				$pr_codes = substr($pr_codes, 0, -2);
				
				$clause[] = "product_code in ({$pr_codes})";
			}
		}
		else {
			// Парентс
			$clause[] = '`parents` = "'.$this->view->parents.'#'.$this->view->id.'#"';	
		}
		
		$bonus_filter = '';
		
		if( $this->view->url == 'bonusnaya-akciya') {
			$limit = 300;
			
			$this->conn->query("SELECT DISTINCT `bonus` FROM `ny_promo_products` order by bonus");
			$bonus_filter_inner = '<li><a href="/bonusnaya-akciya">Все</a></li>';
			
			while( $row = $this->conn->fetch() ) {
				$bonus_filter_inner .= '<li><a href="?bonus='.$row->bonus.'">'.$row->bonus.'</a></li>';
			}
			
			$bonus_filter .= '<ul class="bonus_filter">'.$bonus_filter_inner.'</ul>';
		}
		else	
			$limit = 18;
			
		$pr_html = $sort_list = '';
		
		$url_before = $this->view->url_before.'/'.$this->view->url;
		$url_after = $_SERVER['QUERY_STRING'] ? '?'.$_SERVER['QUERY_STRING'] : '';


			// Избавляемся от пагинации в урле если применен фильтр.
		if( strpos( $url_after, '&p=0' ) ) {
			$url_after = str_replace( '&p=0', '', $url_after );
			successRedirect( array( 'url' => $url_before.$url_after ) );
		}
		
			// Цены
		if( isset( $_GET['mi'] ) )
			$clause[] = '`price_retail` > '.$_GET['mi'];
		if( isset( $_GET['ma'] ) )
			$clause[] = '`price_retail` < '.$_GET['ma'];
	
	
			// Бренды
		if( $this->view->brand_id )
			$clause[] = '`brand_id` = '.$this->view->brand_id;
		elseif( isset( $_GET['br'] ) )
			$clause[] = '`brand_id` IN ( '.implode( ',', $_GET['br'] ).' ) ';
		
		
			// Характеристики
		$where_array = array();
 		if( isset( $_GET['ch'] ) ) {
			foreach( $_GET['ch'] as $field_id => $value_ids ) {
				$where = array();
				foreach( $value_ids as $value_id ) {
					$where[] = '`field_id` = '.$field_id.' AND `value_id` = '.$value_id;
				}
				$where_array[] = '`product_code` IN ( SELECT `product_code` FROM `store_p_charact_datas` WHERE '.implode( ' OR ', $where ).' )';
			}
			$clause[] = implode( ' AND ', $where_array );
		}
		
			// Статус
		if( isset( $_GET['pp'] ) ) {
			$clause[] = '`pp` IN ( '.implode( ',', $_GET['pp'] ).' ) ';
		}

			// Сортировка
		$sorts = array( 
				'pr_a'	=> array( 'title' => 'Цены по возрастанию',	'field' => '`price_retail` ASC' ),
				'pr_d'	=> array( 'title' => 'Цены по убыванию',	'field' => '`price_retail` DESC' ),
				'hit_a'	=> array( 'title' => 'Хитам продаж',		'field' => 'find_in_set(`hit`, "1,0")' ),
			);
		$get = isset( $_GET['sort'] ) ? ( isset( $sorts[$_GET['sort']] ) ? $_GET['sort'] : 'pr_a' ) : 'pr_a';
		foreach( $sorts as $g => $sort )
			$sort_list .= '<option value="'.$g.'"'.( ( $get == $g ) ? ' selected' : '' ).'>'.$sort['title'].'</option>';
			

		$params = array(
			'where'		=> implode( ' AND ', $clause ),
			'order'		=> 'find_in_set(`pp`, "1,2,3,4,5,0"), '.$sorts[$get]['field'],
			'limit'		=> $limit,
			'limit_num'	=> $this->view->paginator_index * $limit 
		);

		$products = getProductList( $params );
		foreach( $products['list'] as $product ) {
			if (array_key_exists($product->product_code, $products['presents'])) {
				$present_name = $products['presents'][$product->product_code]['name'];
				$present_url = $products['presents'][$product->product_code]['url'];
			}
			else
				$present_name = $present_url = '';
				
			if( array_key_exists($product->product_code, $products['credits']) ) {
				$product_credit = $products['credits'][$product->product_code].'<br/>';
			}
			else
				$product_credit = '';
				
			$pr_html .= $this->load->block( 'product', array( 'product' => $product, 'present_name' => $present_name, 'present_url' => $present_url, 'product_credit' => $product_credit ) );
		}

	$this->view->js_on_load[] = '
		/*- Изменение цен в фильтре -*/
		var min_price = parseInt( $("#min_price").val() );
		var max_price = parseInt( $("#max_price").val() );

		$("#price").slider({
			min: min_price,
			max: max_price,
			values: [ parseInt( $("#price__min-cost").val() ) , parseInt( $("#price__max-cost").val() ) ],
			range: true,
			stop: function(event, ui) {
				$("#price__min-cost").val( $("#price").slider("values",0) );
				$("#price__max-cost").val( $("#price").slider("values",1) );
				filterSend();
			},
			slide: function(event, ui){
				$("#price__min-cost").val( $("#price").slider("values",0) );
				$("#price__max-cost").val( $("#price").slider("values",1) );
			}
		});

		$("input#price__min-cost").change(function(){
			var value1 = $("#price__min-cost").val();
			var value2 = $("#price__max-cost").val();

			if(parseInt(value1) > parseInt(value2)){
				value1 = value2;
				$("#price__min-cost").val(value1);
			}
			$("#price").slider("values",0,value1);
		});


		$("#price__max-cost").change(function(){

			var value1 = $("#price__min-cost").val();
			var value2 = $("#price__max-cost").val();

			if (value2 > 10000) { value2 = 100000; $("input#price__max-cost").val(100000)}

			if(parseInt(value1) > parseInt(value2)){
				value2 = value1;
				$("#price__max-cost").val(value2);
			}
			$("#price").slider("values",1,value2);
		});';

		//Изменение оформления заголовка из-за новогодней акции
        if($this->view->templ != 'ny_promo') {
			$my_h1 = '<h1 class="big-title">'.( $this->view->h1 ? $this->view->h1 : $this->view->title ).( $this->view->brand ? ' '.$this->view->brand : '' ).'</h1>';
		}
        else
            $my_h1 = '';

		return	// ivan_baner( 'small-size' ).'
				'<div class="article__top-panel">
					'.$my_h1.
					($this->view->templ != 'ny_promo' ?
					'<dl class="sorting">
						<dt>Сортировать по:</dt>
						<dd>
							<form action="http://happystore.loc'.$_SERVER['REQUEST_URI'].'" method="get">
								<select name="sort" class="b-core-ui-select__select" >'.$sort_list.'</select>
							</form>
						</dd>
					</dl>' : '').
					( ( preg_match('/page/', $_SERVER['REQUEST_URI']) or $this->view->brand != '' or isset($_GET) && count($_GET) > 0 ) ? '' : '<div class="entry">'.$this->view->text1.'</div>').'<div class="entry">'.$bonus_filter.'</div>
				</div>
				<div class="goods-list">
					<ul class="goods-list__inner">'.$pr_html.'</ul>
					'.$this->load->block( 'pagination', array(
						'total'			=> $products['count'], 
						'limit'			=> $limit, 
						'url_before'	=> $url_before.( $this->view->brand_url ? '/'.$this->view->brand_url : '' ), 
						'url_after'		=> $url_after
					)).'
				</div>';
	}
}